<script setup>
import { ref, watch, onMounted } from 'vue';
import { queryEmpApi, addEmpApi, queryEmpById } from '@/api/emp';
import { queryAllApi as queryAllDeptApi } from '../../api/dept';
import { ElMessage, ElMessageBox } from 'element-plus';
import { deleteEmpById, updateEmpApi } from '../../api/emp';




//定义搜索框的数据模型
const searchEmp = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
})

//查询
const search = async () => {
  const result = await queryEmpApi(searchEmp.value.name,
    searchEmp.value.gender,
    searchEmp.value.begin,
    searchEmp.value.end,
    currentPage.value,
    pageSize.value);
  if (result.code) {
    empList.value = result.data.rows;
    total.value = result.data.total;
  }
}

//钩子函数
onMounted(() => {
  search();

  //新增员工和修改员工时都需要查询所有部门，所以直接在页面加载的时候就查询出来
  queryAllDepts();

  //
  getToken();
})


//清除搜索框中的数据
const clear = () => {
  searchEmp.value = {
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: ''
  }
  search();
}


//数据展示,定义空数组
const empList = ref([])




//watch侦听 -searchEmp的date属性
watch(() => searchEmp.value.date, (newVal, oldVal) => {
  if (searchEmp.value.date && searchEmp.value.date.length > 0) {
    searchEmp.value.begin = searchEmp.value.date[0];
    searchEmp.value.end = searchEmp.value.date[1];


  } else {
    searchEmp.value.begin = '';
    searchEmp.value.end = '';
  }

})

/* 分页条 */
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);


/* 分页条相关函数 */
const handleSizeChange = (val) => {
  search();
}
const handleCurrentChange = (val) => {
  search();
}


//新增/修改表单
const employee = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
})

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')


//新增（添加）员工的方法
//将对话框打开，并将标题命名为新增员工
const add = async () => {

  //清空上次不合法的提示
  if (empFormRef.value) {
    empFormRef.value.resetFields();
  }

  dialogVisible.value = true;
  dialogTitle.value = '新增员工';

  //清空上次表单中填写的数据
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: []
  }

}

//定义数组用来动态展示对话框中的选项数据
//职位列表数据（便于维护和管理）
const jobs = ref([{ name: '班主任', value: 1 }, { name: '讲师', value: 2 }, { name: '学工主管', value: 3 }, { name: '教研主管', value: 4 }, { name: '咨询师', value: 5 }])

//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])

//部门列表数据，动态查询
const depts = ref()




//定义方法，用来查询全部的部门信息
const queryAllDepts = async () => {
  const result = await queryAllDeptApi();
  if (result.code) {
    depts.value = result.data;
  }

}

//文件上传
// 图片上传成功后触发,将后端返回数据中的图片地址赋值给employee.value.image
const handleAvatarSuccess = (response) => {
  employee.value.image = response.data
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}


//员工工作经历
const addWorkItem = () => {

  //同一个员工增加一条员工工作经历，相当于往工作经历数组中添加一个元素
  employee.value.exprList.push({ company: '', job: '', begin: '', end: '', exprDate: [] });
}


//删除工作经历
const delWorkItem = (index) => {
  employee.value.exprList.splice(index, 1)

}

//watch侦听，将一个员工的工作经历中的每个工作经历（对象）中的工作日期数组给分开，且同时变化，需要深度侦听
watch(() => employee.value.exprList, (newVal, oldVal) => {
  if (employee.value.exprList && employee.value.exprList.length > 0) {

    //遍历用forEach
    employee.value.exprList.forEach(expr => {
      if (expr.exprDate && expr.exprDate.length > 0) {
        expr.begin = expr.exprDate[0];
        expr.end = expr.exprDate[1];
      } else {
        expr.begin = '';
        expr.end = '';
      }
    })
  }
}, { deep: true })



//表单校验规则
const empFormRef = ref();

//定义表单校验规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '用户名长度应在在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在在2到20个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
})

//保存员工信息
const save = async () => {
  //保存之前, 先校验表单, 校验通过, 再发送请求
  if (!empFormRef) return
  await empFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      //通过

      let result;
      //先判断是否有id,有id就修改，否则就新增
      //员工信息封装到employee对象中了，所以用employee.value.id
      if (employee.value.id) {
        result = await updateEmpApi(employee.value);
      } else {
        result = await addEmpApi(employee.value);
      }


      if (result.code) {

        //成功(关闭会话框)
        dialogVisible.value = false;
        ElMessage.success('保存成功');
        search();
      } else {
        ElMessage.error(result.msg)
      }

    } else { //不通过
      ElMessage.error('表单校验不通过,请检查表单');
    }
  })
}

//根据Id查询回显员工信息
const edit = async (id) => {
  const result = await queryEmpById(id);
  if (result.code) {

    //打开会话框
    dialogVisible.value = true;
    dialogTitle.value = '修改员工';
    employee.value = result.data;

    //判断是否有员工经历
    if (employee.value.exprList && employee.value.exprList.length > 0) {

      //有经历就遍历循环，为begin,end赋值
      employee.value.exprList.forEach(expr => {
        expr.exprDate = [expr.begin, expr.end];
      })
    }


  } else {
    ElMessage.error(result.msg);
  }
}


//根据单个Id删除员工
const deleteById = (id) => {
  ElMessageBox.confirm(
    '您确定要删除该员工吗?',
    '提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {

      //确认删除
      const result = await deleteEmpById(id);
      if (result.code) {
        ElMessage.success('删除成功');
        search();
      } else {
        ElMessage.error(result.msg)
      }

    })
    .catch((err) => {

      //取消删除
      ElMessage.info('操作已取消')

    })

}

//批量删除员工
//定义空数组，用来存储复选时的员工Id
const seleceIds = ref([]);
const handleSelectionChange = (valArr) => {
  seleceIds.value = valArr.map(item => item.id)
}

//根据id批量删除员工信息
const deleteByIds = () => {
  ElMessageBox.confirm(
    '您确定要删除这些员工信息吗?',
    '提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {

      //确认删除
      const result = await deleteEmpById(seleceIds.value);
      if (result.code) {
        ElMessage.success('删除成功');
        search();
      } else {
        ElMessage.error(result.msg)
      }

    })
    .catch((err) => {

      //取消删除
      ElMessage.info('操作已取消')

    })

}

//令牌token
const token = ref('');

//获取token
const getToken = () => {
  const loginUserStr = localStorage.getItem('loginUser');
  if (loginUserStr) {
    token.value = JSON.parse(loginUserStr).token;
  }
}

</script>


<template>
  <h1>员工管理</h1>

  <!-- 表单组件 -->
  <!-- 搜索框 -->
  <div class="search">

    <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchEmp.name" placeholder="请输入用户姓名" clearable />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="searchEmp.gender" placeholder="请选择" clearable>
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="入职日期">
        <el-date-picker v-model="searchEmp.date" type="daterange" unlink-panels range-separator="到"
          start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item>
        <span> <el-button type="primary" @click="search">搜索</el-button></span>
        <span> <el-button type="info" @click="clear">清空</el-button></span>
      </el-form-item>
    </el-form>


    <!-- 表格组件 -->
    <div id="header">
      <el-button type="primary" @click="add">+ 新增学员</el-button>
      <el-button type="danger" @click="deleteByIds">-批量删除</el-button>
    </div>
  </div>
  <br>

  <el-table :data="empList" border style="width: 100%" @selection-change="handleSelectionChange">

    <!-- 复选框 -->
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column property="name" label="姓名" width="120" align="center" />
    <el-table-column property="gender" label="性别" width="100" align="center">
      <template #default="scope">
        {{ scope.row.gender == 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column property="image" label="头像" width="150" align="center">
      <template #default="scope">
        <img :src="scope.row.image" width="40" style="border-radius: 10%;" />
      </template>
    </el-table-column>
    <el-table-column property="deptName" label="所属部门" width="150" align="center" />
    <el-table-column property="job" label="职位" width="150" align="center">
      <template #default="scope">
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else-if="scope.row.job == 5">咨询师</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column property="entryDate" label="入职日期" width="220" align="center" />
    <el-table-column property="updateTime" label="最后操作时间" width="250" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column><br>
  </el-table>

  <!-- 分页条 -->
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40, 50, 100]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />



  <!--=========== 新增/修改员工的对话框==============-->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form :model="employee" :rules="rules" ref="empFormRef" label-width="80px">

      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="employee.username" placeholder="请输入员工用户名，2-20个字"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="employee.name" placeholder="请输入员工姓名，2-10个字"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="employee.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option v-for="gender in genders" :label="gender.name" :value="gender.value"></el-option>

            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="employee.phone" placeholder="请输入员工手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="employee.job" placeholder="请选择职位" style="width: 100%;">
              <el-option v-for="job in jobs" :label="job.name" :value="job.value"></el-option>

            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="employee.salary" placeholder="请输入员工薪资"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="employee.deptId" placeholder="请选择部门" style="width: 100%;">
              <el-option v-for="dept in depts" :label="dept.name" :value="dept.id"></el-option>

            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker v-model="employee.entryDate" type="date" style="width: 100%;" placeholder="选择日期"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
            <el-upload class="avatar-uploader" action="/api/upload" 
              :headers="{ 'token': token }" 
              :show-file-list="false" 
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="employee.image" :src="employee.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 工作经历 -->
      <!-- 第六行 -->
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button type="success" size="small" @click="addWorkItem">+ 添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 ...  工作经历 -->
      <el-row :gutter="3" v-for="(expr, index) in employee.exprList">
        <el-col :span="10">
          <el-form-item size="small" label="时间" label-width="80px">
            <el-date-picker v-model="expr.exprDate" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="公司" label-width="60px">
            <el-input v-model="expr.company" placeholder="请输入公司名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="职位" label-width="60px">
            <el-input v-model="expr.job" placeholder="请输入职位"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button type="danger" @click="delWorkItem(index)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- =====新增员工会话框底部按钮=========-->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>

</template>



<style scoped>
.search {
  margin: 20px;
}

.search .el-form-item .el-button {
  margin-right: 30px;
  /* 可选：增加表单项之间的间距 */
}

.search .el-input,
.search .el-select,
.search .el-date-editor {
  width: 150px;
  /* 设置一个合适的宽度 */
}


.avatar {
  height: 40px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  border-radius: 10px;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>